<script setup lang='ts'>
import { getHouseList, sourceSave, useBaozuList } from '@fl/api/advertising-api/goods-group'
import { SubmitBtn } from '@fl/components'
import { useDicts } from '../../../goods-management//hooks/use-dicts'
import { cloneDeep } from 'lodash-es'

const emits = defineEmits(['refresh'])
const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<number>('id', { required: false })
const state = defineModel<any>('goodsForm', { required: true })

const btnLoading = ref<boolean>(false)
const formRef = ref()
const title = ref<string>('添加')

const { dicts: { PlateType }, useDict } = useDicts()
const projectOptions = ref<any>()
const projectObj = ref<any>() // 选择楼盘后带出来的信息

const houseOptions = ref<any>()
const baozuOptions = ref<any>()
const { data: baozuList } = useBaozuList(visible)

watchEffect(() => {
    title.value = id.value ? '编辑' : '添加'
})

// 好房列表(新)
function getHouseOptions() {
    getHouseList().then((res) => {
        houseOptions.value = cloneDeep(res.rows).reduce((pre, cur) => {
            cur.value = cur.projectId
            cur.label = cur.projectName
            pre.push(cur)
            return pre
        }, [])
    })
}
getHouseOptions()

watchEffect(() => {
    if (baozuList.value) {
        baozuOptions.value = cloneDeep(baozuList.value.rows).reduce((pre, cur) => {
            cur.value = cur.id
            cur.label = cur.goodsName
            pre.push(cur)
            return pre
        }, [])
    }
    if (state.value.plate === '2') {
        projectOptions.value = baozuOptions.value
    }
    else if (state.value.plate === '1') {
        projectOptions.value = houseOptions.value
    }
    else {
        projectOptions.value = []
    }

    title.value = id.value ? '编辑' : '添加'
})

// 选择楼盘/产品
function projectChange(val) {
    const item = projectOptions.value.find(item => item.value === val)
    projectObj.value = {
        projectId: item.value,
        projectName: item.label,
    }
}

// 提交商品
async function submit(formEl) {
    // const valid = await formRef.value.formInstance.validate()
    const valid = await formEl.validate()
    if (valid) {
        if (valid) {
            let msg = ''
            const { activeEnd, activeStart, groupSnapshotId, id, projectName, plate } = state.value
            const params = {
                activeEnd,
                activeStart,
                groupSnapshotId,
                id,
                projectName,
                plate,
                ...unref(projectObj),
            }

            if (id) {
                btnLoading.value = true
                await sourceSave(params).then(() => {
                    msg = '编辑成功'
                }).catch(() => {
                    btnLoading.value = false
                })
            }
            else {
                btnLoading.value = true
                await sourceSave(params).then(() => {
                    msg = '添加成功'
                }).catch(() => {
                    btnLoading.value = false
                })
            }
            if (msg) {
                ElMessage({
                    message: msg,
                    type: 'success',
                })
                emits('refresh', groupSnapshotId)
                visible.value = false
            }
            btnLoading.value = false
        }
        else {
            console.log('error submit!')
        }
    }
}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = undefined
    formRef.value?.resetFields()
}

defineExpose({
    reset,
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="800"
                close-on-press-escape
                :has-footer="false"
                @cancel="cancel"
                @closed="reset"
    >
        <div class="mt20">
            <el-form ref="formRef"
                     :model="state"
                     label-width="140"
                     label-position="right"
            >
                <el-form-item label="业务类型："
                              prop="plate"
                              :rules="{
                                  required: true,
                                  message: '请选择业务类型',
                                  trigger: 'change',
                              }"
                >
                    <el-select v-model="state.plate">
                        <el-option v-for="item in PlateType"
                                   :key="item.value"
                                   :value="item.value"
                                   :label="item.label"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="楼盘/产品名称："
                              prop="projectName"
                              :rules="{
                                  required: true,
                                  message: '请选择',
                                  trigger: 'change',
                              }"
                >
                    <el-select v-model="state.projectName"
                               filterable
                               @change="projectChange"
                    >
                        <el-option v-for="item in projectOptions"
                                   :key="item.value"
                                   :value="item.value"
                                   :label="item.label"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
        </div>

        <div class="mx-auto mt20 flex justify-center">
            <el-button @click="cancel">
                取消
            </el-button>

            <SubmitBtn type="primary"
                       :loading="btnLoading"
                       @click="submit(formRef)"
            >
                提交
            </SubmitBtn>
        </div>
    </PlusDialog>
</template>

<style lang="scss" scoped>
.material-select-dialog {
    height: 88% !important;

    .el-dialog__body {
        height: 80%;
        overflow-y: auto;
    }
}

.material-img {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.material-img:hover {
    border-color: var(--el-color-primary);
}

.el-icon.material-img-icon {
    font-size: 28px;
    color: #8c939d;
    width: 108px;
    height: 108px;
    text-align: center;
}

.adImg-box {
    width: 108px;
    height: 108px;
    display: flex;
    align-items: center;
    background-color: rgb(0 0 0 / 10%);
    overflow: hidden;
    margin-right: 12px;
}

.json-label {
    display: block;
    width: 100px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
    text-align: right;
}
</style>
